from django.utils import simplejson
from google.appengine.ext import webapp
from gaexmlrpctransport import GAEXMLRPCTransport
import xmlrpclib
from google.appengine.api import urlfetch
import cgi
import logging

import sys, os
sys.path.insert(0, __file__.split(os.sep + "GMT" + os.sep)[0])

import import_wrapper
from GMT.messaging.xmlpickle import pickle, unpickle
from GMT.messaging import messages  

class TestPage(webapp.RequestHandler):
    """ Used for tests """
    def get(self):
#        # "https://www.cs.tau.ac.il/cgi-bin/cgiwrap/~nirgrin2/example_1.2.cgi"
##        testsvr = xmlrpclib.ServerProxy("http://kite.cs.tau.ac.il:40404", GAEXMLRPCTransport())
#        testsvr = xmlrpclib.ServerProxy("https://www.cs.tau.ac.il/cgi-bin/cgiwrap/~nirgrin2/forward.py", GAEXMLRPCTransport())
#        params = {"Name" : "Dave Warner", "Occupation" : "Programmer/Analyst"}
#        self.response.out.write(testsvr.dump_params(params))
#        self.response.out.write(testsvr.dump_response('test', 32))

        request = messages.Request(True)
        res = urlfetch.fetch("https://www.cs.tau.ac.il/cgi-bin/cgiwrap/~nirgrin2/forward.py",
                             method=urlfetch.POST,
                             payload=pickle(request),
                             headers={'Content-Type': 'text/xml'},
                             deadline=10)
        #logging.info(res.content)
        response = unpickle(res.content)
        self.response.out.write(response.code) 
        
class TestJSON(webapp.RequestHandler):
    def get(self):
#        self.response.out.write("{\"Name\" : \"Rowan\", \"Breed\" : \"Labrador Retriever\", \"Hobbies\" : [\"fetching\", \"swimming\", \"tugging\", \"eating\"]}")
#        self.response.out.write("{\"Top senders\": \"{cols:[{id:'address',label:'Contact E-mail',type:'string'},{id:'count',label:'Count',type:'number'}]}\", \"Top recipients\": \"{cols:[{id:'address',label:'Contact E-mail',type:'string'},{id:'count',label:'Count',type:'number'}]}")
#        return
        request = messages.Request(True)
#       res = urlfetch.fetch("http://localhost:40404",
        res = urlfetch.fetch("http://www.cs.tau.ac.il/cgi-bin/cgiwrap/~nirgrin2/forward.py",        
                             method=urlfetch.POST,
                             payload=pickle(request),
                             headers={'Content-Type': 'text/xml'},
                             deadline=10)
        logging.info(res.content)
        response = unpickle(res.content)
        self.response.out.write(simplejson.dumps(response.data)) 
